import axios from 'axios';
import { message } from 'antd';
import { useUserStore } from '../store/user';

const request = axios.create({
  baseURL: '',
  timeout: 10000,
});

// 请求拦截器，自动加token
request.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    console.log('拦截器token:', token);
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token;
    }
    console.log('最终headers:', config.headers);
    return config;
  },
  error => Promise.reject(error)
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 200) {
      message.error(res.message || '请求失败');
      return Promise.reject(new Error(res.message || '请求失败'));
    }
    return res;
  },
  (error) => {
    message.error(error.message || '请求失败');
    return Promise.reject(error);
  }
);

export default request; 